import { gameObject } from './gameObject';
import { wall } from './wall';
import { snake } from './snake';

export class gameMap extends gameObject {
    constructor(ctx, parent, store) {//画布
        super();
        this.ctx = ctx;
        this.parent = parent;
        this.store = store;
        this.L = 0; //相对距离

        this.rows = 13;//地图大小
        this.cols = 14;

        this.innerWallCount = 20;//障碍物数量
        this.walls = [];

        this.snakes = [
            new snake({ id: 0, color: "#4876ec", r: this.rows - 2, c: 1 }, this),
            new snake({ id: 1, color: "#f94848", r: 1, c: this.cols - 2 }, this)
        ];
    }
    checkReady() {
        //当都静止且已获取操作时才能移动
        for (const snake of this.snakes) {
            if (snake.status !== "idle") return false;
            if (snake.direction === -1) return false;
        }
        return true;
    }
    /*checkConnectivity(g, sx, sy, tx, ty) {
        if (sx == tx && sy == ty) return true;
        g[sx][sy] = true;

        let dx = [-1, 0, 1, 0], dy = [0, 1, 0, -1];
        for (let i = 0; i < 4; i++) {
            let x = sx + dx[i], y = sy + dy[i];
            if (!g[x][y] && this.checkConnectivity(g, x, y, tx, ty))
                return true;
        }
        return false;
    }
    
    createWalls() {
        const g = [];
        for (let r = 0; r < this.rows; r++) {
            g[r] = [];
            for (let c = 0; c < this.cols; c++) {
                g[r][c] = false;
            }
        }

        // 给四周加上障碍物
        for (let r = 0; r < this.rows; r++) {
            g[r][0] = g[r][this.cols - 1] = true;
        }

        for (let c = 0; c < this.cols; c++) {
            g[0][c] = g[this.rows - 1][c] = true;
        }

        // 创建随机障碍物
        for (let i = 0; i < this.innerWallCount / 2; i++) {
            for (let j = 0; j < 1000; j++) {
                let r = parseInt(Math.random() * this.rows);
                let c = parseInt(Math.random() * this.cols);
                if (g[r][c] || g[this.rows - 1 - r][this.cols - 1 - c]) continue;
                if (r == this.rows - 2 && c == 1 || r == 1 && c == this.cols - 2)
                    continue;

                g[r][c] = g[this.rows - 1 - r][this.cols - 1 - c] = true;
                break;
            }
        }

        const copy_g = JSON.parse(JSON.stringify(g));
        if (!this.checkConnectivity(copy_g, this.rows - 2, 1, 1, this.cols - 2))
            return false;

        for (let r = 0; r < this.rows; r++) {
            for (let c = 0; c < this.cols; c++) {
                if (g[r][c]) {
                    this.walls.push(new wall(r, c, this));
                }
            }
        }

        return true;
    }*/

    createWalls() {
        
        const g = this.store.state.Pk.map;
        for (let r = 0; r < this.rows; r++) {
            for (let c = 0; c < this.cols; c++) {
                if (g[r][c]) {
                    this.walls.push(new wall(r, c, this));
                }
            }
        }
    }
    start() {
        this.listenEvents();
        /*for (let i = 0; i < 1000; i++) {
            if (this.createWalls()) break;
        }*/
       this.createWalls();
    }
    updateSize() {
        this.L = parseInt(
            Math.min(
                this.parent.clientWidth / this.cols,
                this.parent.clientHeight / this.rows
            )
        );
        this.ctx.canvas.width = this.L * this.cols;
        this.ctx.canvas.height = this.L * this.rows;
    }
    nextStep() {
        for (const snake of this.snakes) {
            snake.nextStep();
        }
    }

    checkVaild(cell) { //检测蛇是否可以移动
        for (const wall of this.walls) {
            if (wall.r === cell.r && wall.c === cell.c)
                return false;
        }
        for (const snake of this.snakes) {
            let k = snake.cells.length;
            if (!snake.checkTail())   // 当蛇尾会前进的时候，蛇尾不要判断
                k--
            
            for (let i = 0; i < k; i++) {
                if (snake.cells[i].r === cell.r && snake.cells[i].c === cell.c)
                    return false;
            }
        }
        return true;
    }
    update() {//每一帧执行一次
        this.updateSize();
        if (this.checkReady()) {
            this.nextStep();//下一回合
            this.store.commit("startTime");
        }
        this.render();
    }
    listenEvents() {
        this.ctx.canvas.focus();
        this.ctx.canvas.addEventListener("keydown", e => {
            let d = -1;
            let fangxiang = "无";
            if (e.key === 'w') d=0,fangxiang = "上";
            else if (e.key === 'd') d=1,fangxiang="右";
            else if (e.key === 's') d=2,fangxiang="下";
            else if (e.key === 'a') d=3,fangxiang="左";
            this.store.commit("updateDirectionShow",fangxiang);
            if(d >= 0){
                this.store.state.Pk.socket.send(JSON.stringify({
                    event:"move",
                    direction:d,
                    id:this.store.state.User.id,
                }))
            }
        });
    }
    render() {
        const colorEven = '#aad751';
        const colorOdd = '#a2d149';
        for (let r = 0; r < this.rows; r++)
            for (let c = 0; c < this.cols; c++) {
                if ((r + c) % 2 == 0) this.ctx.fillStyle = colorEven;
                else this.ctx.fillStyle = colorOdd;
                this.ctx.fillRect(c * this.L, r * this.L, this.L, this.L);
            }
    }
}